package com.igeek.compus.study.dao;

import com.igeek.compus.study.entity.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {

    public User userInfo(String username,String password)throws Exception{
        Class.forName("com.mysql.cj.jdbc.Driver");

        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/compus?seUnicode=true&characterEncoding=utf8"
        ,"root","123456");

        String sql = "select * from t_user01 where username=? and password = ? limit=1";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);

        ResultSet resultSet = preparedStatement.executeQuery();

        User user = null;

        while (resultSet.next()){
            int id = resultSet.getInt("id");
            String username1 = resultSet.getString("username");
            String password1 = resultSet.getString("password");
            String sex = resultSet.getString("sex");
            String phone = resultSet.getString("phone");
            String email = resultSet.getString("email");

            user =new User();
            user.setId(id);
            user.setUsername(username);
            user.setPassword(password);
            user.setSex(sex);
            user.setPhone(phone);
            user.setEmail(email);

            System.out.println(user);
        }
        return user;
    }

    /**
     * 添加用户
     * @param user
     * @return
     * @throws Exception
     */
    public int addUser(User user) throws Exception{
        Class.forName("com.mysql.cj.jdbc.Driver");

        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/compus?useUnicode=true&characterEncoding=utf8","root","123456");

        String sql = "insert into t_user1 (username , password , sex , phone , email)"+"values(?,?,?,?,?)";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString( 1, user.getUsername());
        preparedStatement.setString( 2, user.getPassword());
        preparedStatement.setString( 3, user.getSex());
        preparedStatement.setString( 4, user.getPhone());
        preparedStatement.setString( 5, user.getEmail());

        return preparedStatement.executeUpdate();
    }

    public static void main(String[] args)throws Exception{
        UserDao userDao = new UserDao();
        User user = new User();
        user.setUsername("李四");
        user.setPassword("123456");
        user.setSex("男");
        user.setPhone("123456");
        user.setEmail("123456");
        userDao.addUser(user);

    }
}
